/*
 * @Author: 追逐的娃 kangchao_php@163.com
 * @Date: 2024-07-03 10:39:15
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-07-11 20:56:18
 * @FilePath: \main_demo\vue-project\src\utils\request.js
 * @Description:
 *
 */
import axios from 'axios'
import { useUserStore } from '@/stores'
import { Message } from '@arco-design/web-vue'

//baseUrl超时时间配置
const instance = axios.create({
  baseURL: '/api', //域名已经在vite.config.js中解决跨域的时候指定了
  // baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 5000
  // headers: headers
})

//全局注入token
instance.interceptors.request.use(
  (config) => {
    let store = useUserStore()
    //获取token
    const token = store.token
    //请求头设置 根据后端要求设置
    if (token) config.headers['token'] = token
    return config
  },
  (e) => Promise.reject(e)
)

//处理返回数据，token失效跳回到登录页
instance.interceptors.response.use(
  (response) => {
    return {
      code: response.status,
      Message: response.statusText,
      data: response.request.responseType == 'blob' ? response.data : response.data.data
    }
  },
  (error) => {
    let store = useUserStore()
    const msg = error.response.data.msg || '请求失败'

    //根据错误判断
    if (msg == '非法token，请先登录') {
      //调用退出方法
      store.logout()
      location.reload()
    }
    console.log(msg)
    Message.error(msg)
    return Promise.reject(error)
  }
)
export default instance
